<?php

namespace Plugin\XunSearch\Utils;

use Flarum\Discussion\Discussion;
use Flarum\Post\Post;

use Flarum\Settings\SettingsRepositoryInterface;

class XunSearchUtils
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;

    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
    }

    function getXuSearch(): \XS
    {
        $index_server = $this->settings->get('xunsearch.index_server');
        $search_server = $this->settings->get('xunsearch.search_server');

        return new \XS("project.name = flarum
server.index = $index_server
server.search = $search_server

[id]
type = id

[discId]
index = self

[title]
index = self

[content]
type = body

[time]
type = numeric
index = self

[discTime]
type = numeric
index = self

[count]
type = numeric
index = self");
    }

    // 获取搜索引擎索引
    function getIndex(): \XSIndex
    {
        return $this->getXuSearch()->index;
    }

    // 获取搜索
    function getSearch(): \XSSearch
    {
        return $this->getXuSearch()->search;
    }

    // 获取文档
    function getDocument(Discussion $discussion, Post $post, $count): \XSDocument
    {
        $data = array(
            "id" => $post->id,
            "discId" => $discussion->id,
            "title" => $discussion->title,
            "content" => $post->content,
            "time" => strtotime($post->created_at),
            "discTime" => strtotime($post->discussion->created_at),
            "count" => $count
        );
        $doc = new \XSDocument;
        $doc->setFields($data);
        return $doc;
    }
}
